//    Openbravo POS is a point of sales application designed for touch screens.
//    Copyright (C) 2007-2009 Openbravo, S.L.
//    http://www.openbravo.com/product/pos
//
//    This file is part of Openbravo POS.
//
//    Openbravo POS is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Openbravo POS is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with Openbravo POS.  If not, see <http://www.gnu.org/licenses/>.

package com.openbravo.pos.sales;

import cn.ekuma.epos.bean.util.RoleSwingUtil;
import cn.ekuma.epos.bean.util.sale.TicketLineHelper;
import cn.ekuma.epos.businesslogic.RoleUtil;
import cn.ekuma.epos.datalogic.I_DataLogicSales;
import cn.ekuma.epos.datalogic.I_DataLogicSystem;
import cn.ekuma.security.I_SecurityManager;
import cn.ekuma.swing.dialog.AbstractKeyBoardJDialog;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.MessageInf;

import java.awt.Component;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.KeyStroke;


import com.openbravo.pos.base.AppLocal;
import com.openbravo.pos.base.AppView;
import com.openbravo.pos.panels.JObjectListFinder;
import com.openbravo.bean.AppUser;
import com.openbravo.bean.infobean.UserInfo;
import com.openbravo.bean.sales.TicketLine;

import javax.swing.JLabel;

import com.openbravo.editor.JEditorString;

import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.ImageIcon;

/**
 * @author adrianromero
 */
public class JProductLineEdit extends AbstractKeyBoardJDialog {

    private TicketLine returnLine;
    private TicketLine m_oLine;
    private boolean m_bunitsok;
    private boolean m_bpriceok;
    private int active;
    private JEditorString lotNo;
    private I_DataLogicSales dlSales;
    private final static int activeCount = 3;

    /**
     * Creates new form JProductLineKeyBoardEdit
     *
     * @wbp.parser.constructor
     */
    private JProductLineEdit(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        // Inicializo los componentes
        initComponents();
    }

    /**
     * Creates new form JProductLineKeyBoardEdit
     */
    private JProductLineEdit(java.awt.Dialog parent, boolean modal) {
        super(parent, modal);
        // Inicializo los componentes
        initComponents();
    }

    private TicketLine init(final AppView app, TicketLine oLine, I_DataLogicSales dlSales, final I_DataLogicSystem dlSystem, I_SecurityManager security)
            throws BasicException {

        if (oLine.getTaxInfo() == null) {
            throw new BasicException(
                    AppLocal.getIntString("message.cannotcalculatetaxes"));
        }

        this.dlSales = dlSales;

        m_oLine = oLine.copyTicketLine();
        m_bunitsok = true;
        m_bpriceok = true;
        boolean editable = security.hasPermissionByName(RoleUtil.Permission_EDIT_TICKET_LINE);
        setLineEditAble(editable);
        m_jName.setText(m_oLine.getProperty("product.name"));
        m_jUnits.setDoubleValue(oLine.getMultiply());
        m_jPrice.setDoubleValue(TicketLineHelper.getPrice(oLine));
        m_jPriceTax.setDoubleValue(TicketLineHelper.getPriceTax(oLine));
        m_jTaxrate.setText(oLine.getTaxInfo().getName());
        jPriceRant.setDoubleValue(oLine.getPriceRate() * 100);
        lotNo.setText(oLine.getLotNo());
        jSaleMan.setText(oLine.getSaleMan());

        m_jName.addPropertyChangeListener("Edition", new RecalculateName());
        m_jUnits.addPropertyChangeListener("Edition", new RecalculateUnits());
        m_jPrice.addPropertyChangeListener("Edition", new RecalculatePrice());
        m_jPriceTax.addPropertyChangeListener("Edition",
                new RecalculatePriceTax());
        jPriceRant.addPropertyChangeListener("Edition",
                new RecalculatePriceRant());

        m_jName.addEditorKeys(m_jKeys);
        m_jUnits.addEditorKeys(m_jKeys);
        m_jPrice.addEditorKeys(m_jKeys);
        m_jPriceTax.addEditorKeys(m_jKeys);
        jPriceRant.addEditorKeys(m_jKeys);
        lotNo.addEditorKeys(m_jKeys);

        active = 1;
        m_jUnits.activate();

        KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0);
        ActionListener actionListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                boolean editable = RoleSwingUtil.hasPermission(getRootPane(), (AppUser) app
                        .getAppUserView().getUser(), dlSystem, RoleUtil.Permission_EDIT_TICKET_LINE);
                setLineEditAble(editable);
            }
        };
        getRootPane().registerKeyboardAction(actionListener, stroke,
                JComponent.WHEN_IN_FOCUSED_WINDOW);

        printTotals();

        getRootPane().setDefaultButton(m_jButtonOK);
        returnLine = null;
        setVisible(true);
        return returnLine;
    }

    private void setLineEditAble(boolean editable) {
        m_jName.setEnabled(m_oLine.getProductID() == null && editable);
        m_jPrice.setEnabled(editable);
        m_jPriceTax.setEnabled(editable);
        jPriceRant.setEnabled(editable);
    }

    private void printTotals() {

        if (m_bunitsok && m_bpriceok) {
            m_jSubtotal.setText(TicketLineHelper.printSubValue(m_oLine));
            m_jTotal.setText(TicketLineHelper.printValue(m_oLine));
            m_jButtonOK.setEnabled(true);
        } else {
            m_jSubtotal.setText(null);
            m_jTotal.setText(null);
            m_jButtonOK.setEnabled(false);
        }
    }

    @Override
    protected void enterKeyProc() {
        if (m_jButtonOK.isEnabled())
            m_jButtonOKActionPerformed(null);
    }

    @Override
    protected void escapeKeyProc() {
        dispose();
    }

    @Override
    protected void upKeyProc() {
        switch (active) {
            case 1:
                active = activeCount;
                if (jPriceRant.isEnabled()) {
                    m_jUnits.deactivate();
                    m_jPrice.deactivate();
                    jPriceRant.activate();
                    break;
                }
            case 2:
                active--;
                m_jUnits.activate();
                m_jPrice.deactivate();
                jPriceRant.deactivate();
                break;

            case 3:
                active--;
                if (m_jPrice.isEnabled()) {
                    m_jUnits.deactivate();
                    m_jPrice.activate();
                    jPriceRant.deactivate();
                }
        }
    }

    @Override
    protected void downKeyProc() {
        switch (active) {
            case 1:
                active++;
                if (m_jPrice.isEnabled()) {
                    m_jUnits.deactivate();
                    m_jPrice.activate();
                    jPriceRant.deactivate();
                    break;
                }
            case 2:
                active++;
                if (jPriceRant.isEnabled()) {
                    m_jUnits.deactivate();
                    m_jPrice.deactivate();
                    jPriceRant.activate();
                    break;
                }
            case 3:
                m_jUnits.activate();
                m_jPrice.deactivate();
                jPriceRant.deactivate();
                active = 1;
        }
    }

    private class RecalculatePriceRant implements PropertyChangeListener {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            Double value = jPriceRant.getDoubleValue();
            if (value == null || value < 0 || value > 100) {
                m_bunitsok = false;
            } else {
                m_oLine.setPriceRate(value / 100);
                m_bunitsok = true;
            }
            printTotals();
        }
    }

    private class RecalculateUnits implements PropertyChangeListener {
        public void propertyChange(PropertyChangeEvent evt) {
            Double value = m_jUnits.getDoubleValue();
            if (value == null || value == 0.0) {
                m_bunitsok = false;
            } else {
                m_oLine.setMultiply(value);
                m_bunitsok = true;
            }

            printTotals();
        }
    }

    private class RecalculatePrice implements PropertyChangeListener {
        public void propertyChange(PropertyChangeEvent evt) {

            Double value = m_jPrice.getDoubleValue();
            if (value == null || value == 0.0) {
                m_bpriceok = false;
            } else {
                TicketLineHelper.setPrice(m_oLine, value);
                m_jPriceTax.setDoubleValue(TicketLineHelper
                        .getPriceTax(m_oLine));
                m_bpriceok = true;
            }

            printTotals();
        }
    }

    private class RecalculatePriceTax implements PropertyChangeListener {
        public void propertyChange(PropertyChangeEvent evt) {

            Double value = m_jPriceTax.getDoubleValue();
            if (value == null || value == 0.0) {
                // m_jPriceTax.setValue(m_oLine.getPriceTax());
                m_bpriceok = false;
            } else {
                TicketLineHelper.setPriceTax(m_oLine, value);
                m_jPrice.setDoubleValue(TicketLineHelper.getPrice(m_oLine));
                m_bpriceok = true;
            }

            printTotals();
        }
    }

    private class RecalculateName implements PropertyChangeListener {
        public void propertyChange(PropertyChangeEvent evt) {
            m_oLine.setProperty("product.name", m_jName.getText());
        }
    }


    public static TicketLine showMessage(Component parent, AppView app,
                                         TicketLine oLine, I_DataLogicSales dlSales, final I_DataLogicSystem dlSystem, I_SecurityManager security) throws BasicException {

        Window window = getWindow(parent);

        JProductLineEdit myMsg;
        if (window instanceof Frame) {
            myMsg = new JProductLineEdit((Frame) window, true);
        } else {
            myMsg = new JProductLineEdit((Dialog) window, true);
        }
        return myMsg.init(app, oLine, dlSales, dlSystem, security);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed"
    // desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel5 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        m_jName = new com.openbravo.editor.JEditorString();
        m_jUnits = new com.openbravo.editor.JEditorDouble();
        m_jPrice = new com.openbravo.editor.JEditorCurrency();
        m_jPriceTax = new com.openbravo.editor.JEditorCurrency();
        m_jTaxrate = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        m_jTotal = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        m_jSubtotal = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jPriceRant = new com.openbravo.editor.JEditorIntegerPositive();
        jPanel1 = new javax.swing.JPanel();
        m_jButtonOK = new javax.swing.JButton();
        m_jButtonCancel = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        m_jKeys = new com.openbravo.editor.JEditorKeys();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(AppLocal.getIntString("label.editline")); // NOI18N

        jPanel5.setLayout(new java.awt.BorderLayout());

        jPanel2.setLayout(null);

        jLabel1.setText(AppLocal.getIntString("label.price")); // NOI18N
        jPanel2.add(jLabel1);
        jLabel1.setBounds(10, 80, 90, 15);

        jLabel2.setText(AppLocal.getIntString("label.units")); // NOI18N
        jPanel2.add(jLabel2);
        jLabel2.setBounds(10, 50, 90, 15);

        jLabel3.setText(AppLocal.getIntString("label.pricetax")); // NOI18N
        jPanel2.add(jLabel3);
        jLabel3.setBounds(10, 110, 90, 15);

        jLabel4.setText(AppLocal.getIntString("label.item")); // NOI18N
        jPanel2.add(jLabel4);
        jLabel4.setBounds(10, 20, 90, 15);
        jPanel2.add(m_jName);
        m_jName.setBounds(100, 20, 270, 25);
        jPanel2.add(m_jUnits);
        m_jUnits.setBounds(100, 50, 240, 25);
        jPanel2.add(m_jPrice);
        m_jPrice.setBounds(100, 80, 240, 25);
        jPanel2.add(m_jPriceTax);
        m_jPriceTax.setBounds(100, 110, 240, 25);

        m_jTaxrate.setBackground(javax.swing.UIManager.getDefaults().getColor(
                "TextField.disabledBackground"));
        m_jTaxrate.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        m_jTaxrate.setBorder(javax.swing.BorderFactory.createCompoundBorder(
                javax.swing.BorderFactory
                        .createLineBorder(javax.swing.UIManager.getDefaults()
                                .getColor("Button.darkShadow")),
                javax.swing.BorderFactory.createEmptyBorder(1, 4, 1, 4)));
        m_jTaxrate.setOpaque(true);
        m_jTaxrate.setPreferredSize(new java.awt.Dimension(150, 25));
        m_jTaxrate.setRequestFocusEnabled(false);
        jPanel2.add(m_jTaxrate);
        m_jTaxrate.setBounds(100, 170, 210, 25);

        jLabel5.setText(AppLocal.getIntString("label.tax")); // NOI18N
        jPanel2.add(jLabel5);
        jLabel5.setBounds(10, 170, 90, 15);

        jLabel6.setText(AppLocal.getIntString("label.totalcash")); // NOI18N
        jPanel2.add(jLabel6);
        jLabel6.setBounds(10, 230, 90, 15);

        m_jTotal.setBackground(javax.swing.UIManager.getDefaults().getColor(
                "TextField.disabledBackground"));
        m_jTotal.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        m_jTotal.setBorder(javax.swing.BorderFactory.createCompoundBorder(
                javax.swing.BorderFactory
                        .createLineBorder(javax.swing.UIManager.getDefaults()
                                .getColor("Button.darkShadow")),
                javax.swing.BorderFactory.createEmptyBorder(1, 4, 1, 4)));
        m_jTotal.setOpaque(true);
        m_jTotal.setPreferredSize(new java.awt.Dimension(150, 25));
        m_jTotal.setRequestFocusEnabled(false);
        jPanel2.add(m_jTotal);
        m_jTotal.setBounds(100, 230, 210, 25);

        jLabel7.setText(AppLocal.getIntString("label.subtotalcash")); // NOI18N
        jPanel2.add(jLabel7);
        jLabel7.setBounds(10, 200, 90, 15);

        m_jSubtotal.setBackground(javax.swing.UIManager.getDefaults().getColor(
                "TextField.disabledBackground"));
        m_jSubtotal.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        m_jSubtotal.setBorder(javax.swing.BorderFactory.createCompoundBorder(
                javax.swing.BorderFactory
                        .createLineBorder(javax.swing.UIManager.getDefaults()
                                .getColor("Button.darkShadow")),
                javax.swing.BorderFactory.createEmptyBorder(1, 4, 1, 4)));
        m_jSubtotal.setOpaque(true);
        m_jSubtotal.setPreferredSize(new java.awt.Dimension(150, 25));
        m_jSubtotal.setRequestFocusEnabled(false);
        jPanel2.add(m_jSubtotal);
        m_jSubtotal.setBounds(100, 200, 210, 25);

        jLabel8.setText(AppLocal.getIntString("label.priceRate")); // NOI18N
        jPanel2.add(jLabel8);
        jLabel8.setBounds(10, 140, 90, 15);
        jPanel2.add(jPriceRant);
        jPriceRant.setBounds(100, 140, 240, 25);

        jPanel5.add(jPanel2, java.awt.BorderLayout.CENTER);

        JLabel label = new JLabel(AppLocal.getIntString("label.lotNo"));
        label.setBounds(10, 270, 90, 15);
        jPanel2.add(label);

        lotNo = new JEditorString();
        lotNo.setBounds(100, 266, 240, 25);
        jPanel2.add(lotNo);

        JLabel label_1 = new JLabel("销售员");
        label_1.setBounds(10, 295, 54, 15);
        jPanel2.add(label_1);

        jSaleMan = new JTextField();
        jSaleMan.setEditable(false);
        jSaleMan.setBounds(100, 295, 172, 21);
        jPanel2.add(jSaleMan);
        jSaleMan.setColumns(10);

        JButton btnNewButton = new JButton("");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                changeSaleMan();
            }
        });
        btnNewButton.setIcon(new ImageIcon(JProductLineEdit.class.getResource("/com/openbravo/images/edit_group.png")));
        btnNewButton.setBounds(281, 294, 49, 23);
        jPanel2.add(btnNewButton);

        jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        m_jButtonOK.setIcon(new javax.swing.ImageIcon(getClass().getResource(
                "/com/openbravo/images/button_ok.png"))); // NOI18N
        m_jButtonOK.setText(AppLocal.getIntString("Button.OK")); // NOI18N
        m_jButtonOK.setFocusPainted(false);
        m_jButtonOK.setFocusable(false);
        m_jButtonOK.setMargin(new java.awt.Insets(8, 16, 8, 16));
        m_jButtonOK.setRequestFocusEnabled(false);
        m_jButtonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jButtonOKActionPerformed(evt);
            }
        });
        jPanel1.add(m_jButtonOK);

        m_jButtonCancel.setIcon(new javax.swing.ImageIcon(getClass()
                .getResource("/com/openbravo/images/button_cancel.png"))); // NOI18N
        m_jButtonCancel.setText(AppLocal.getIntString("Button.Cancel")); // NOI18N
        m_jButtonCancel.setFocusPainted(false);
        m_jButtonCancel.setFocusable(false);
        m_jButtonCancel.setMargin(new java.awt.Insets(8, 16, 8, 16));
        m_jButtonCancel.setRequestFocusEnabled(false);
        m_jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jButtonCancelActionPerformed(evt);
            }
        });
        jPanel1.add(m_jButtonCancel);

        jPanel5.add(jPanel1, java.awt.BorderLayout.SOUTH);

        getContentPane().add(jPanel5, java.awt.BorderLayout.CENTER);

        jPanel3.setLayout(new java.awt.BorderLayout());

        jPanel4.setLayout(new javax.swing.BoxLayout(jPanel4,
                javax.swing.BoxLayout.Y_AXIS));
        jPanel4.add(m_jKeys);

        jPanel3.add(jPanel4, java.awt.BorderLayout.NORTH);

        getContentPane().add(jPanel3, java.awt.BorderLayout.EAST);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit()
                .getScreenSize();
        setBounds((screenSize.width - 580) / 2, (screenSize.height - 362) / 2,
                580, 422);
    }// </editor-fold>//GEN-END:initComponents

    protected void changeSaleMan() {
        try {
            List allUser = dlSales.listPeopleVisible();
            JObjectListFinder userList = JObjectListFinder.newJDialog(this);
            UserInfo tempUser = (UserInfo) userList.showUserList(allUser);
            if (tempUser != null) {
                jSaleMan.setText(tempUser.getId());
            } else
                jSaleMan.setText(null);
        } catch (BasicException ex) {
            MessageInf msg = new MessageInf(ex);
            msg.show(this);
        }
    }

    private void m_jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_m_jButtonCancelActionPerformed

        dispose();

    }// GEN-LAST:event_m_jButtonCancelActionPerformed

    private void m_jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_m_jButtonOKActionPerformed
        m_oLine.setLotNo(lotNo.getText());
        m_oLine.setSaleMan(jSaleMan.getText());
        returnLine = m_oLine;
        dispose();

    }// GEN-LAST:event_m_jButtonOKActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private com.openbravo.editor.JEditorIntegerPositive jPriceRant;
    private javax.swing.JButton m_jButtonCancel;
    private javax.swing.JButton m_jButtonOK;
    private com.openbravo.editor.JEditorKeys m_jKeys;
    private com.openbravo.editor.JEditorString m_jName;
    private com.openbravo.editor.JEditorCurrency m_jPrice;
    private com.openbravo.editor.JEditorCurrency m_jPriceTax;
    private javax.swing.JLabel m_jSubtotal;
    private javax.swing.JLabel m_jTaxrate;
    private javax.swing.JLabel m_jTotal;
    private com.openbravo.editor.JEditorDouble m_jUnits;
    private JTextField jSaleMan;
}
